/** 
    Copyright 2010 Henrik Andersson
    
    This file is part of Loopist.

    Loopist is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Loopist is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Loopist.  If not, see <http://www.gnu.org/licenses/>.
*/


package se.dinamic.loopist;
import java.util.Vector;
import java.nio.ShortBuffer;

/** Mixes and limiting assigned tracks. */
public class Mixer {
	private final Vector<Track> _tracks = new Vector<Track>();
	private Listener _listener;

	
	public Mixer() {
		
	}
	
	/** Adds a track to the mixer. */
	public void addTrack(Track track) { _tracks.add(track); }
	
	/** Get track reference by index in mixer. */
	public Track getTrack(int t) { return _tracks.get(t); }
	
	public int getTrackIndex(Track t) { return _tracks.indexOf(t); }
	
	/** Get the count of tracks in mixer. */
	public int getTrackCount() { return _tracks.size(); }
	
	/** Sets the listener reference of mixer. \see Mixer.Listener */
	public void setListener( Mixer.Listener listener) { _listener=listener; }
	
	/** A listener interface of Mixer */
	static public interface Listener {
		/** Fired when last sample of track has mixed... */
		public void onTrackEnd();
	}
	
	// Fill buffer with mix of tracks
	public void fill(ShortBuffer buffer) {
		
		buffer.position(0);
		int m;
		
		for(int i=0;i< buffer.capacity();i++) {
			m=0;
			
			// mix tracks...
			for(int t=0;t<_tracks.size();t++)
				/*if( ! _tracks.get(t).isRecording() )*/ {
					m+=_tracks.get(t).getSample();
					m=m>>2;
				}
			
			// add mixed sample
			buffer.put( (short)m );
			
			// Check if track is on last sample
			if( _tracks.get(0).isEndOfTrack() && _listener != null ) {
				_listener.onTrackEnd();
			}
				
		}
	}
}